package model

import (
	"gitee.com/csingo/cDB"
	"github.com/gin-gonic/gin"
	"time"
)

type Versions struct {
	ID        uint64     `gorm:"column:id" json:"id"`
	PackageId uint64     `gorm:"column:package_id" json:"package_id"`
	Name      string     `gorm:"column:name" json:"name"`
	CreatedAt *time.Time `gorm:"column:created_at;<-:create" json:"created_at"`
	UpdatedAt *time.Time `gorm:"column:updated_at" json:"updated_at"`
}

func (i *Versions) Connection() string {
	return "default"
}

func (i *Versions) Save(ctx *gin.Context, packageId uint64, vers []string) error {
	err := i.DelByPackageId(ctx, packageId)
	if err != nil {
		return err
	}

	data := []*Versions{}
	for _, ver := range vers {
		data = append(data, &Versions{
			PackageId: packageId,
			Name:      ver,
		})
	}

	err = cDB.Query(i).CreateInBatches(data, len(data)).Error
	return err
}

func (i *Versions) DelByPackageId(ctx *gin.Context, packageId uint64) error {
	err := cDB.Query(i).Where("package_id = ?", packageId).Delete(&Versions{}).Error
	return err
}

func (i *Versions) FindByPackageIds(ctx *gin.Context, packageId []uint64) ([]*Versions, error) {
	res := []*Versions{}
	err := cDB.Query(i).
		Where("package_id IN ?", packageId).
		Order("name").
		Find(&res).
		Error

	return res, err
}
